package com.etennis.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.etennis.constants.AppHttpCodeEnum;
import com.etennis.constants.IOEnum;

import com.etennis.pojos.ResponseResult;
import com.etennis.pojos.dto.LoginDTO;
import com.etennis.pojos.dto.app.UserDTO;
import com.etennis.pojos.entity.Member;
import com.etennis.pojos.entity.Record;
import com.etennis.pojos.vo.app.UserLoginVO;
import com.etennis.pojos.vo.app.UserVO;
import com.etennis.security.LoginUserDetails;
import com.etennis.service.IMemberService;
import com.etennis.service.IRecordService;
import com.etennis.utils.IOUtils;
import com.etennis.utils.JwtUtil;
import com.etennis.utils.RedisCache;
import com.etennis.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;
@RestController
@RequestMapping("/app/user")
@Slf4j
@Api(tags = "用户端-个人模块接口")
public class UserController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IMemberService iMemberService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private IOUtils ioUtils;
    @GetMapping("/mine")
    @ApiOperation("个人信息")
    public ResponseResult<UserVO> mine(){
        UserVO userVO=iMemberService.mine();
        return ResponseResult.okResult(userVO);
    }
    @PutMapping("/update")
    @ApiOperation("修改个人信息")
    public ResponseResult update(@RequestBody UserDTO userDTO){
        iMemberService.updateUser(userDTO);
        return ResponseResult.okResult();
    }
    @PostMapping("/uploadIcon")
    public ResponseResult uploadIcon(@RequestParam("img") MultipartFile img){
        try {
            String returnPath=ioUtils.uploadMedia(img,IOEnum.IS_USER_AVATAR);
            Member member=new Member(SecurityUtils.getLoginUserId(),returnPath);
            iMemberService.updateById(member);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult();
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseResult<UserLoginVO> appLogin(@RequestBody LoginDTO loginDTO){
        return login(loginDTO);
    }
    public ResponseResult<UserLoginVO> login(LoginDTO loginDTO) {
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginDTO.getAccount(),loginDTO.getPassword());
        Authentication authentication=authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authentication)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR,"login error");
        }
        LoginUserDetails loginUser = (LoginUserDetails) authentication.getPrincipal();

        String userId = loginUser.getUser().getAccount();
        Member member=loginUser.getUser();
        String jwt= JwtUtil.createJWT(userId);
        redisCache.setCacheObject(userId,loginUser);
        Integer win=recordService.count(new LambdaQueryWrapper<Record>().eq(Record::getWinA1Id,member.getId()).or().eq(Record::getWinA2Id,member.getId()));
        Integer lose=recordService.count(new LambdaQueryWrapper<Record>().eq(Record::getLoseB1Id,member.getId()).or().eq(Record::getLoseB2Id,member.getId()));
        UserLoginVO userVo=new UserLoginVO(jwt,member.getId(),member.getIcon(),member.getName(),member.getClubId(),win,lose+win);
        return ResponseResult.okResult(userVo);
    }

    @GetMapping("/logout")
    public ResponseResult logout(){
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        LoginUserDetails loginClubDetails= (LoginUserDetails) authentication.getPrincipal();
        String userId=loginClubDetails.getUser().getAccount();
        redisCache.deleteObject(userId);
        return ResponseResult.okResult();

    }


}
